package com.atguigu.yygh.sms.service.impl;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCode;
import com.atguigu.yygh.sms.service.SmsService;
import com.atguigu.yygh.sms.utils.HttpUtils;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {
    /**
     * 发送手机验证码(鼎信官网示例)
     *
     * @param phone
     * @param code
     */
    @Override
    public void send(String phone, String code) {
        String host = "http://dingxin.market.alicloudapi.com";
        String path = "/dx/sendSms";
        String method = "POST";
        String appcode = "80891d07b0134eeeaeb46cbbf43b29f2";
        Map<String, String> headers = new HashMap<>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<>();
        querys.put("mobile", phone);
        querys.put("param", "code:" + code);
        querys.put("tpl_id", "TP1711063"); //验证码模板
        Map<String, String> bodys = new HashMap<>();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());

            String data = EntityUtils.toString(response.getEntity());
            log.info(data);
            Gson gson = new Gson();
            HashMap<String, String> resultMap = gson.fromJson(data, HashMap.class);
            String returnCode = resultMap.get("return_code");

            if(!"00000".equals(returnCode)){
                log.error("短信发送失败：return_code = " + returnCode);
                throw new YyghException(ResultCode.ERROR, "短信发送失败");
            }

        } catch (Exception e) {
            throw new YyghException(ResultCode.ERROR, "短信发送失败",e);
        }
    }
}
